package cn.liontalk.producer;

import cn.liontalk.constant.Constant;
import cn.liontalk.dao.BrokerMessageDao;
import cn.liontalk.entity.Order;
import com.rabbitmq.client.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author ZhouZhe
 * @version 1.0
 * @description rabbitmq 消息发送端
 * @date 2018-12-11 21:43
 **/
@Component
public class RabbitmqOrderSender {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private BrokerMessageDao messageDao;


    //回调函数: confirm确认
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback(){
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("correlationData : " + correlationData);

            String messageId = correlationData.getId();
            if(ack){

                //如果confirm 返回成功,则进行更新
                messageDao.changeBrokerMessageLogStatus(messageId, Constant.SEND_SUCCESS,new Date());
            }else{
                // 失败之后 重试或者补偿手段
                System.out.println("出现异常，需要处理。。。。");
            }
        }
    };


   public void sendOrder(Order order){
    // 通过实现 ConfirmCallback 接口，消息发送到 Broker 后触发回调，确认消息是否到达 Broker 服务器，也就是只确认是否正确到达 Exchange 中
       rabbitTemplate.setConfirmCallback(confirmCallback);
       //消息唯一ID
       CorrelationData correlationData = new CorrelationData(order.getMessageId());
       rabbitTemplate.convertAndSend("order-exchange", "order.ABCD", order, correlationData);
   }

}
